# ISPQueryInterface
# coding=utf-8
import execjs
import xml.etree.ElementTree as ET
import httplib as hlib

# 流量查询
class RateOfFlowQuery(object):
    def __init__(self):
        self.config = None

    def call_array(self, array, call_method, config, para):
        result = array.call(call_method, para['user_cell'], config['user'], config['password'], config['method'])
        return result

    def combin_para_string(self, config, para, pass_word_value, sign_value):
        return self.combine_keypair('method', config['method'], '&') + self.combine_keypair('userId', config[
            'user'], '&') + self.combine_keypair('passWord', pass_word_value, '&') + self.combine_keypair('tel',
                                                                                                          para[
                                                                                                              'user_cell'],
                                                                                                          '&') + self.combine_keypair(
            'startDate', para['start_date'], '&') + self.combine_keypair('endDate', para['end_date'],
                                                                         '&') + self.combine_keypair(
            'sign', sign_value)

    def get_config(self):
        if self.config is None:
            root = ET.fromstring(open('Configure.xml').read())
            result = filter(lambda x: x.attrib['id'] == type(self).__name__, root.iter('Config'))
            user_id = result[0][0].text
            pwd = result[0][1].text
            mtd = result[0][2].text
            # 获取加密字符串
            eword = result[0][3].text
            adr = result[0][4].text
            prt = result[0][5].text
            url = result[0][6].text
            self.config = dict(user=user_id, password=pwd, method=mtd, enc_word=eword, address=adr, port=prt, url=url)
        return self.config

    def combine_keypair(self, key, value, tail=''):
        keypair = "%s=%s"
        return keypair % (key, value) + tail

    def create_array_obj(self):
        return """
        var myarray = new Array();
        function getArray(){
            for(i=0; i<arguments.length; i +=1){
                myarray.push(arguments[i]);
            }
        return myarray;
        }
        """

    def combine_query_string(self, para):
        request_string = "http://%s:%s/%s?%s"
        source = open('des.js').read()
        cts = execjs.compile(source)
        ary_source = self.create_array_obj()
        get_ary = execjs.compile(ary_source)
        config = self.get_config()
        array = self.call_array(get_ary, 'getArray', config, para)
        arr_order = cts.call('naturalOrdering', array)
        sign_value = cts.call('strEnc', arr_order, config['enc_word'])
        pass_word_value = cts.call('strEnc', config['password'], config['enc_word'])
        para_string = self.combin_para_string(config, para, pass_word_value, sign_value)
        return request_string % (config['address'], config['port'], config['url'], para_string)

    def query(self, user_cell, start_date='20150101', end_date='20150131'):
        para = self.get_config()
        conn = hlib.HTTPConnection(para['address'], int(para['port']))
        conn.request("GET", self.combine_query_string(
            dict(user_cell=user_cell, start_date='20150101', end_date='20150131')))
        response = conn.getresponse()
        return response.read()

# 余额查询
class BalanceQuery(RateOfFlowQuery):
    def combin_para_string(self, config, para, pass_word_value, sign_value):
        return self.combine_keypair('method', config['method'], '&') + self.combine_keypair('tel', para['user_cell'],
                                                                                            '&') + self.combine_keypair(
            'userId', config[
                'user'], '&') + self.combine_keypair('passWord', pass_word_value, '&') + self.combine_keypair(
            'sign', sign_value)

    def combine_query_string(self, para):
        request_string = "http://%s:%s/%s?%s"
        source = open('des.js').read()
        cts = execjs.compile(source)
        ary_source = self.create_array_obj()
        get_ary = execjs.compile(ary_source)
        config = self.get_config()
        array = self.call_array(get_ary, 'getArray', config, para)
        arr_order = cts.call('naturalOrdering', array)
        sign_value = cts.call('strEnc', arr_order, config['enc_word'])
        pass_word_value = cts.call('strEnc', config['password'], config['enc_word'])
        para_string = self.combin_para_string(config, para, pass_word_value, sign_value)
        return request_string % (config['address'], config['port'], config['url'], para_string)

    def query(self, user_cell):
        para = self.get_config()
        conn = hlib.HTTPConnection(para['address'], int(para['port']))
        conn.request("GET", self.combine_query_string(dict(user_cell=user_cell)))
        response = conn.getresponse()
        return response.read()


class OrderFlow(RateOfFlowQuery):
    def call_array(self, array, call_method, config, para):
        result = array.call(call_method, para['user_cell'], config['user'], config['password'], config['method'],
                            para['flow_value'])
        return result

    def combin_para_string(self, config, para, pass_word_value, sign_value):
        return self.combine_keypair('method', config['method'], '&') + self.combine_keypair('userId', config[
            'user'], '&') + self.combine_keypair('passWord', pass_word_value, '&') + self.combine_keypair('accessNumber',
                                                                                                          para[
                                                                                                              'user_cell'],
                                                                                                          '&') + self.combine_keypair(
            'flowValue', para['flow_value'], '&') + self.combine_keypair(
            'sign', sign_value)

    def query(self, user_cell, order_flow_package):
        para = self.get_config()
        conn = hlib.HTTPConnection(para['address'], int(para['port']))
        print(self.combine_query_string(dict(user_cell=user_cell, flow_value=order_flow_package)))
        conn.request("GET", self.combine_query_string(dict(user_cell=user_cell, flow_value=order_flow_package)))
        response = conn.getresponse()
        return response.read()

    @property
    def get_order_flow_package_set(self):
        return {1: "M2M(数据)2 元叠加包--专网版(2014)", 2: "M2M(数据)1 元叠加包--专网版(2014)", 3: "M2M(数据)10 元叠加包--专网版(2014)",
                4: "M2M(数据)30 元叠加包--专网版(2014)", 5: "M2M(数据)50 元叠加包--专网版(2014)", 6: "M2M(数据)300 元加油包(1 年)--专网版(2014)",
                7: "M2M(数据)600 元加油包(1 年)--专网版(2014)", 8: "M2M(数据)200 元加油包(6 个月)--专网版(2014)",
                9: "M2M(数据)300 元加油包(6 个月)--专网版(2014)", 10: "M2M(数据)70 元加油包(3 个月)--专网版(2014)",
                11: "M2M(数据)100 元加油包(3 个月)--专网版(2014)"}
